package com.moon.interface_api.utils;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import sun.misc.BASE64Decoder;
import sun.misc.BASE64Encoder;

import javax.crypto.Cipher;
import javax.crypto.SecretKey;
import javax.crypto.spec.SecretKeySpec;
import java.util.Date;

/**
 *Created by chengliang on 2018/7/24.
 */
public class TokenUtils {

    private static final Logger logger = LoggerFactory.getLogger(TokenUtils.class);
    
    private static String key = "AICHILEE";
    
    private static String way = "DES";
    
    private static String charset = "UTF-8";


    
    public static final String createToken(String plainText) {
        try {

            SecretKey secretKey=new SecretKeySpec(key.getBytes(), way);

          /*SecretKeyFactory sf = SecretKeyFactory.getInstance("AES");
          SecretKey secretKey = sf.generateSecret(new DESKeySpec(way.getBytes("utf-8")));*/
            Cipher cipher = Cipher.getInstance(way+"/ECB/PKCS5Padding");
            cipher.init(Cipher.ENCRYPT_MODE, secretKey);
            byte[] p = plainText.getBytes(charset);
            byte[] result = cipher.doFinal(p);
            BASE64Encoder encoder = new BASE64Encoder();
            String encoded = encoder.encode(result);
            return encoded;
        } catch (Exception e) {
            logger.error(plainText+"生成token异常");
            throw new RuntimeException(e);
        }
    }

    public static final String getUserInfo(String cipherText) {
        SecretKey secretKey=new SecretKeySpec(key.getBytes(), way);
        try {
            Cipher cipher = Cipher.getInstance(way+"/ECB/PKCS5Padding");
            cipher.init(Cipher.DECRYPT_MODE, secretKey);
            BASE64Decoder decoder = new BASE64Decoder();
            byte[] c = decoder.decodeBuffer(cipherText);
            byte[] result = cipher.doFinal(c);
            String plainText = new String(result, charset);
            return plainText;
        } catch (Exception e) {
            logger.error(cipherText+"获取用户信息异常");
            throw new RuntimeException(e);
        }
    }
    
    
    public static void main(String[] args){
        String token = TokenUtils.createToken("186218189895"+","+new Date().getTime());
        System.out.println(token);
        String userInfo = TokenUtils.getUserInfo(token);
        System.out.println(userInfo);
    }
}
